/**
 * 大麦抢票助手前端应用
 */
class DamaiApp {
    constructor() {
        this.apiBase = '/api';
        this.currentUser = null;
        this.currentShow = null;
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.checkLoginStatus();
        this.setupToasts();
    }

    setupEventListeners() {
        // 登录表单
        const loginForm = document.getElementById('loginForm');
        if (loginForm) {
            loginForm.addEventListener('submit', this.handleLogin.bind(this));
        }

        // 搜索表单
        const searchForm = document.getElementById('searchForm');
        if (searchForm) {
            searchForm.addEventListener('submit', this.handleSearch.bind(this));
        }

        // 抢票表单
        const rushForm = document.getElementById('rushForm');
        if (rushForm) {
            rushForm.addEventListener('submit', this.handleRush.bind(this));
        }

        // 实时更新按钮
        const updateBtn = document.getElementById('updateStatus');
        if (updateBtn) {
            updateBtn.addEventListener('click', this.updateMonitorStatus.bind(this));
        }
    }

    setupToasts() {
        // 创建toast容器
        const toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        toastContainer.style.zIndex = '1050';
        document.body.appendChild(toastContainer);
        this.toastContainer = toastContainer;
    }

    showToast(message, type = 'info') {
        const toastId = `toast-${Date.now()}`;
        const toastHtml = `
            <div id="${toastId}" class="toast align-items-center text-white bg-${type} border-0" role="alert">
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            </div>
        `;
        
        this.toastContainer.insertAdjacentHTML('beforeend', toastHtml);
        const toastElement = document.getElementById(toastId);
        const toast = new bootstrap.Toast(toastElement);
        toast.show();
        
        // 自动移除
        toastElement.addEventListener('hidden.bs.toast', () => {
            toastElement.remove();
        });
    }

    async checkLoginStatus() {
        try {
            const response = await fetch(`${this.apiBase}/auth/status`);
            const data = await response.json();
            
            if (data.logged_in) {
                this.currentUser = data.user;
                this.updateLoginUI();
            }
        } catch (error) {
            console.error('检查登录状态失败:', error);
        }
    }

    async handleLogin(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const credentials = {
            username: formData.get('username'),
            password: formData.get('password'),
            remember_me: formData.get('remember_me') === 'on'
        };

        try {
            const response = await fetch(`${this.apiBase}/auth/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(credentials)
            });

            const data = await response.json();
            
            if (data.success) {
                this.currentUser = data.user;
                this.showToast('登录成功！', 'success');
                
                // 延迟跳转
                setTimeout(() => {
                    window.location.href = '/ticket';
                }, 1000);
            } else {
                this.showToast(data.message || '登录失败', 'danger');
            }
        } catch (error) {
            this.showToast('网络错误，请重试', 'danger');
        }
    }

    updateLoginUI() {
        const userInfo = document.getElementById('userInfo');
        if (userInfo && this.currentUser) {
            userInfo.innerHTML = `
                <span class="navbar-text me-3">
                    欢迎, ${this.currentUser.username}
                </span>
                <button class="btn btn-outline-danger btn-sm" onclick="app.logout()">
                    退出
                </button>
            `;
        }
    }

    async logout() {
        try {
            await fetch(`${this.apiBase}/auth/logout`, { method: 'POST' });
            this.currentUser = null;
            window.location.href = '/login';
        } catch (error) {
            console.error('退出登录失败:', error);
        }
    }

    async handleSearch(e) {
        e.preventDefault();
        
        const keyword = document.getElementById('searchKeyword').value;
        const loadingBtn = document.getElementById('searchBtn');
        
        loadingBtn.disabled = true;
        loadingBtn.innerHTML = '<span class="loading-spinner"></span> 搜索中...';

        try {
            const response = await fetch(`${this.apiBase}/ticket/search?q=${encodeURIComponent(keyword)}`);
            const data = await response.json();
            
            this.displaySearchResults(data.shows || []);
        } catch (error) {
            this.showToast('搜索失败，请重试', 'danger');
        } finally {
            loadingBtn.disabled = false;
            loadingBtn.innerHTML = '搜索';
        }
    }

    displaySearchResults(shows) {
        const resultsContainer = document.getElementById('searchResults');
        if (!resultsContainer) return;

        if (shows.length === 0) {
            resultsContainer.innerHTML = `
                <div class="text-center py-5">
                    <i class="fas fa-search fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">未找到相关演出</h5>
                </div>
            `;
            return;
        }

        const html = shows.map(show => `
            <div class="col-md-6 col-lg-4 mb-4">
                <div class="card show-card">
                    <img src="${show.poster}" class="card-img-top" alt="${show.name}">
                    <div class="card-body">
                        <h5 class="card-title">${show.name}</h5>
                        <p class="card-text text-muted small">${show.description || ''}</p>
                        <div class="mb-2">
                            <i class="fas fa-map-marker-alt text-muted"></i>
                            <small>${show.venue}</small>
                        </div>
                        <div class="mb-2">
                            <i class="fas fa-calendar text-muted"></i>
                            <small>${show.date} ${show.time}</small>
                        </div>
                        <div class="mb-3">
                            <span class="price-tag">¥${show.min_price}-${show.max_price}</span>
                        </div>
                        <button class="btn btn-primary btn-sm w-100" onclick="app.selectShow('${show.id}')">
                            选择此演出
                        </button>
                    </div>
                </div>
            </div>
        `).join('');

        resultsContainer.innerHTML = html;
    }

    async selectShow(showId) {
        try {
            const response = await fetch(`${this.apiBase}/ticket/show/${showId}`);
            const data = await response.json();
            
            if (data.success) {
                this.currentShow = data.show;
                this.displayShowDetails(data.show);
            }
        } catch (error) {
            this.showToast('获取演出详情失败', 'danger');
        }
    }

    displayShowDetails(show) {
        const detailsContainer = document.getElementById('showDetails');
        if (!detailsContainer) return;

        detailsContainer.innerHTML = `
            <div class="card">
                <div class="row g-0">
                    <div class="col-md-4">
                        <img src="${show.poster}" class="img-fluid rounded-start" alt="${show.name}">
                    </div>
                    <div class="col-md-8">
                        <div class="card-body">
                            <h5 class="card-title">${show.name}</h5>
                            <p class="card-text">${show.description || ''}</p>
                            <div class="mb-2">
                                <strong>场馆：</strong>${show.venue}
                            </div>
                            <div class="mb-2">
                                <strong>地址：</strong>${show.address}
                            </div>
                            <div class="mb-3">
                                <strong>场次：</strong>
                                <div class="mt-1">
                                    ${show.sessions.map(session => 
                                        `<span class="session-badge">${session.date} ${session.time}</span>`
                                    ).join('')}
                                </div>
                            </div>
                            <div class="mb-3">
                                <strong>价位：</strong>
                                <div class="mt-1">
                                    ${show.price_ranges.map(range => 
                                        `<span class="price-tag">¥${range.price}</span>`
                                    ).join('')}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    async handleRush(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const rushConfig = {
            show_id: this.currentShow?.id,
            session_id: formData.get('session'),
            price_range: formData.get('price_range'),
            ticket_count: parseInt(formData.get('ticket_count')),
            rush_time: formData.get('rush_time') || null,
            auto_submit: formData.get('auto_submit') === 'on'
        };

        try {
            const response = await fetch(`${this.apiBase}/ticket/rush`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(rushConfig)
            });

            const data = await response.json();
            
            if (data.success) {
                this.showToast('抢票任务已创建', 'success');
                this.startMonitor(data.task_id);
            } else {
                this.showToast(data.message || '创建任务失败', 'danger');
            }
        } catch (error) {
            this.showToast('网络错误，请重试', 'danger');
        }
    }

    async updateMonitorStatus() {
        try {
            const response = await fetch(`${this.apiBase}/monitor/status`);
            const data = await response.json();
            
            this.displayMonitorStatus(data);
        } catch (error) {
            console.error('获取监控状态失败:', error);
        }
    }

    displayMonitorStatus(data) {
        const statusContainer = document.getElementById('monitorStatus');
        if (!statusContainer) return;

        statusContainer.innerHTML = `
            <div class="row">
                <div class="col-md-3">
                    <div class="monitor-stats">
                        <h3>${data.active_tasks || 0}</h3>
                        <p>活跃任务</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="monitor-stats">
                        <h3>${data.success_count || 0}</h3>
                        <p>成功订单</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="monitor-stats">
                        <h3>${data.failed_count || 0}</h3>
                        <p>失败次数</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="monitor-stats">
                        <h3>${data.total_tickets || 0}</h3>
                        <p>总票数</p>
                    </div>
                </div>
            </div>
        `;

        // 更新日志
        this.updateLogs(data.logs || []);
    }

    updateLogs(logs) {
        const logsContainer = document.getElementById('monitorLogs');
        if (!logsContainer) return;

        const html = logs.map(log => `
            <div class="log-entry log-${log.level}">
                <small class="text-muted">${log.timestamp}</small>
                <span>${log.message}</span>
            </div>
        `).join('');

        logsContainer.innerHTML = html;
        logsContainer.scrollTop = logsContainer.scrollHeight;
    }
}

// 初始化应用
const app = new DamaiApp();